import argparse
import numpy as np
from scipy.interpolate import interp1d
from scipy.optimize import brentq
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt

def plot_roc_curve(fpr, tpr):
    roc_auc = auc(fpr, tpr)

    plt.figure(figsize=(10,8))
    plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.4f)' % roc_auc)
    plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
    plt.xlim([-0.01, 1.01])
    plt.ylim([-0.01, 1.01])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Roc Curve')
    plt.legend(loc="lower right")
    plt.show()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--score_path', help='score path', type=str, default="score.txt")
    args = parser.parse_args()

    data = np.loadtxt(args.score_path, str)
    label = data.T[0].astype(int)
    score = data.T[1].astype(float)

    fpr, tpr, thresholds = roc_curve(label, score, pos_label=1)
    eer = brentq(lambda x: 1.0 - x - interp1d(fpr, tpr)(x), 0.0, 1.0)
    threshold = interp1d(fpr, thresholds)(eer)
    print("Adversarial Attack EER: {:.2f}% with threshold {:.2f}".format(eer*100, threshold))

    scores = data.T[2:].astype(float)
    score = np.mean(scores, axis=0)
    fpr, tpr, thresholds = roc_curve(label, score, pos_label=1)
    eer = brentq(lambda x: 1.0 - x - interp1d(fpr, tpr)(x), 0.0, 1.0)
    threshold = interp1d(fpr, thresholds)(eer)
    print("Voting EER: {:.2f}% with threshold {:.2f}".format(eer*100, threshold))
